package com.lc.afbx.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lc.afbx.BaseApplication;
import com.lc.afbx.R;
import com.lc.afbx.conn.GetApiShowVehicle;
import com.lc.afbx.conn.PostIDCard;
import com.lc.afbx.conn.PostVehicleCard;
import com.lc.afbx.dialog.PictureDialog;
import com.lc.afbx.dialog.ShowPicDialog;
import com.lc.afbx.util.Base64Encoder;
import com.lc.afbx.util.DateTimePickDialogUtil;
import com.lc.afbx.util.MEditTextListener;
import com.lc.afbx.util.MyToast;
import com.lc.afbx.util.PictureUtil;
import com.lc.afbx.util.PrefrenceConfig;
import com.lc.afbx.util.Validator;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilLog;
import com.zcx.helper.util.UtilMD5;
import com.zcx.helper.util.UtilToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2016/5/23.
 */
public class BusinessInsuranceFillInfoActivity extends BasePictureActivity implements View.OnClickListener {

    private EditText useNature;
    private EditText carType;
    private TextView vehicle_origin; //车辆产地

    private List<String> natureList;
    private List<String> vehicletypeList;
    private int i;
    //存放base64 图片的map
    private HashMap<Integer, String> picMap;

    //车辆产地的数据源
    private List<String> areaList;

    private PictureDialog dialog;

    //车辆类型请求来的数据  pop里用
    private GetApiShowVehicle.Info mInfo;


    private PostVehicleCard postVehicleCard = new PostVehicleCard(new AsyCallBack<PostVehicleCard.VehicleCardEntity>() {


        @Override
        public void onSuccess(String toast, int type, PostVehicleCard.VehicleCardEntity vehicleCardEntity) throws Exception {


            if (!TextUtils.isEmpty(vehicleCardEntity.plateno) && !TextUtils.isEmpty(vehicleCardEntity.vehicletype) && !TextUtils.isEmpty(vehicleCardEntity.usecharacter) && !TextUtils.isEmpty(vehicleCardEntity.engineno) && !TextUtils.isEmpty(vehicleCardEntity.vin) && !TextUtils.isEmpty(vehicleCardEntity.model) && !TextUtils.isEmpty(vehicleCardEntity.registerdate) && !TextUtils.isEmpty(vehicleCardEntity.usecharacter)) {

                plate_num.setText(vehicleCardEntity.plateno);
                carType.setText(vehicleCardEntity.vehicletype);//这个要判断 传数字还是汉字
                useNature.setText(vehicleCardEntity.usecharacter);
                engine_num.setText(vehicleCardEntity.engineno);
                vin_code.setText(vehicleCardEntity.vin);
                brand_model.setText(vehicleCardEntity.model);
                registTime.setText(vehicleCardEntity.registerdate);

//                carType.setTag("1");//这瞎写的  以后要判断



                business_show_driverCard_iv.setVisibility(View.VISIBLE);
                business_show_driverCard_iv.setImageBitmap(PictureUtil.getSmallBitmap(picMap.get(2)));
                ((Button) findViewById(R.id.driverCard_submit)).setText("已选择");

            } else {

                MyToast.showToast("行驶证识别失败", context);

                business_show_driverCard_iv.setVisibility(View.GONE);
                picMap.put(2, null);
                ((Button) findViewById(R.id.driverCard_submit)).setText("上传");

            }



        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.showToast("行驶证识别失败", context);

            business_show_driverCard_iv.setVisibility(View.GONE);
            picMap.put(2, null);
            ((Button) findViewById(R.id.driverCard_submit)).setText("上传");

        }

    });


    private PostIDCard postIDCard = new PostIDCard(new AsyCallBack<PostIDCard.IdCardInfoEntity>() {
        @Override
        public void onSuccess(String toast, int type, PostIDCard.IdCardInfoEntity idCardInfoEntity) throws Exception {

//            String code, result, name, gender, people, byear, bmonth, bday, address, idnumber, authority, validdate, age;

            if (!TextUtils.isEmpty(idCardInfoEntity.name) && !TextUtils.isEmpty(idCardInfoEntity.idnumber) && !TextUtils.isEmpty(idCardInfoEntity.address)) {

                name.setText(idCardInfoEntity.name);
                id_number.setText(idCardInfoEntity.idnumber);
                address.setText(idCardInfoEntity.address);

                ((Button) findViewById(R.id.idCard_submit)).setText("已选择");
                business_idcard_show_iv.setVisibility(View.VISIBLE);
                business_idcard_show_iv.setImageBitmap(PictureUtil.getSmallBitmap(picMap.get(1)));

            } else {

                MyToast.showToast("身份证识别失败", context);

                picMap.put(1, null);
                business_idcard_show_iv.setVisibility(View.GONE);
                ((Button) findViewById(R.id.idCard_submit)).setText("上传");
            }

        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            MyToast.showToast("身份证识别失败", context);

            picMap.put(1, null);
            business_idcard_show_iv.setVisibility(View.GONE);
            ((Button) findViewById(R.id.idCard_submit)).setText("上传");

        }
    });

//    //这个是请求 车辆类型，使用性质的接口
//    private GetApiShowVehicle getApiShowVehicle = new GetApiShowVehicle(new AsyCallBack<GetApiShowVehicle.Info>() {
//        @Override
//        public void onSuccess(String toast, int type, GetApiShowVehicle.Info info) throws Exception {
//            natureList = new ArrayList<>();
//            vehicletypeList = new ArrayList<>();
//
//            mInfo = info;
//            for (int i = 0; i < info.data.useNatureList.size(); i++) {
//                natureList.add(info.data.useNatureList.get(i).title);
//            }
//            for (int i = 0; i < info.data.vehicletypeList.size(); i++) {
//                vehicletypeList.add(info.data.vehicletypeList.get(i).title);
//            }
//            //默认显示数据的第一条
//            useNature.setText(info.data.useNatureList.get(0).title);
//            useNature.setTag("1");
//            carType.setText(info.data.vehicletypeList.get(0).title);
//            carType.setTag(info.data.vehicletypeList.get(0).id);
//        }
//
//        @Override
//        public void onFail(String toast, int type) throws Exception {
//
//            UtilToast.show(context, toast);
//
//        }
//    });

    private TextView registTime;
    private EditText applicant;
    private EditText name;
    private EditText id_number;
    private EditText tel;
    private EditText address;
    private EditText brand_model;
    private EditText plate_num;
    private EditText vin_code;
    private EditText engine_num;
    private EditText passengers;
    private EditText weight;
    private EditText driving_area;

    private ImageView business_idcard_show_iv;
    private ImageView business_show_driverCard_iv;
    private ImageView business_show_peopleCar_iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shouye_shangyexian_tianxiexinxi);

        initView();

        setListener();

//        getApiShowVehicle.type = PrefrenceConfig.TWO;
//        getApiShowVehicle.execute(this);


        useNature.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().equals("营运")) {

                    findViewById(R.id.weight_shangyexian_rl).setVisibility(View.VISIBLE);
                    useNature.setTag("1");


                } else if (s.toString().equals("非营运")) {

                    findViewById(R.id.weight_shangyexian_rl).setVisibility(View.GONE);
                    useNature.setTag("2");

                } else {

                    MyToast.showToast("请填写 营运或非营运", context) ;
                }

            }
        });

        business_idcard_show_iv = (ImageView) findViewById(R.id.business_idcard_show_iv);
        business_show_driverCard_iv = (ImageView) findViewById(R.id.business_show_driverCard_iv);
        business_show_peopleCar_iv = (ImageView) findViewById(R.id.business_show_peopleCar_iv);
        business_idcard_show_iv.setOnClickListener(this);
        business_show_driverCard_iv.setOnClickListener(this);
        business_show_peopleCar_iv.setOnClickListener(this);

    }

    private void setListener() {

//        useNature.setOnClickListener(this);
//        carType.setOnClickListener(this);
        vehicle_origin.setOnClickListener(this);
        registTime.setOnClickListener(this);

        applicant.addTextChangedListener(new MEditTextListener(context, 16, applicant));//投保人
        //insurant_info  这个列表
//        name.addTextChangedListener(new MEditTextListener(context, 16, name));          //被保险人名称
//        id_number.addTextChangedListener(new MEditTextListener(context, 18, id_number));//身份证号
        tel.addTextChangedListener(new MEditTextListener(context, 11, tel));            //电话号
//        address.addTextChangedListener(new MEditTextListener(context, 30, address));    //地址


        brand_model.addTextChangedListener(new MEditTextListener(context, 20, brand_model));//厂牌型号
        plate_num.addTextChangedListener(new MEditTextListener(context, 10, plate_num));     //号牌号码
        vin_code.addTextChangedListener(new MEditTextListener(context, 20, vin_code));      // vin 码
        engine_num.addTextChangedListener(new MEditTextListener(context, 20, engine_num));  //发动机编号

        passengers.addTextChangedListener(new MEditTextListener(context, 2, passengers));   //核定载客
        weight.addTextChangedListener(new MEditTextListener(context, 10, weight));           //核定载质量
        driving_area.addTextChangedListener(new MEditTextListener(context, 30, driving_area));//行驶区域

    }

    private void initView() {

        dialog = new PictureDialog(context) {
            @Override
            protected void onCamera() {
                startCamera(null);
            }

            @Override
            protected void onAlbum() {
                startAlbum(null);
            }
        };
        picMap = new HashMap<>();

        areaList = new ArrayList<>();
        areaList.add("国产");
        areaList.add("进口");
        areaList.add("合资车");

        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.idCard_submit).setOnClickListener(this);
        findViewById(R.id.driverCard_submit).setOnClickListener(this);
        findViewById(R.id.peopleCar_submit).setOnClickListener(this);
        findViewById(R.id.shouye_btn_shangyexian_tianxiexinxi_xiayibu).setOnClickListener(this);

        useNature = ((EditText) findViewById(R.id.useNature_shangxian));
        carType = ((EditText) findViewById(R.id.vehicleType_shangxian));
        vehicle_origin = ((TextView) findViewById(R.id.vehicle_origin));
        registTime = ((TextView) findViewById(R.id.regtime));

        // 下面是填写的信息
        applicant = ((EditText) findViewById(R.id.applicant));
        //被保险人信息  这个列表
        name = ((EditText) findViewById(R.id.name));
        id_number = ((EditText) findViewById(R.id.id_number));
        tel = ((EditText) findViewById(R.id.tel));
        address = ((EditText) findViewById(R.id.address));
        // 车辆信息
        brand_model = ((EditText) findViewById(R.id.brand_model));
        plate_num = ((EditText) findViewById(R.id.plate_num));
        vin_code = ((EditText) findViewById(R.id.vin_code));
        engine_num = ((EditText) findViewById(R.id.engine_num));
        passengers = ((EditText) findViewById(R.id.passengers));
        weight = ((EditText) findViewById(R.id.weight));
        driving_area = ((EditText) findViewById(R.id.driving_area));


    }

    @Override
    public void onClick(View view) {

        Intent intent = null;
        switch (view.getId()) {

            case R.id.back:
                finish();
                return;

            case R.id.business_idcard_show_iv:

                new ShowPicDialog(this, picMap.get(1)).show();

                return;

            case R.id.business_show_driverCard_iv:

                new ShowPicDialog(this, picMap.get(2)).show();

                return;

            case R.id.business_show_peopleCar_iv:

                new ShowPicDialog(this, picMap.get(3)).show();

                return;

            case R.id.regtime:
                DateTimePickDialogUtil dialogUtil = new DateTimePickDialogUtil(this, null);
                dialogUtil.dateTimePicKDialog(registTime);

                return;

            case R.id.idCard_submit:
                i = 1;
                dialog.show();
                return;
            case R.id.driverCard_submit:
                i = 2;
                dialog.show();
                return;
            case R.id.peopleCar_submit:
                i = 3;
                dialog.show();
                return;

            case R.id.vehicleType_shangxian:
                view.setTag("1");
                showPop(view);
                return;
            case R.id.useNature_shangxian:
                view.setTag("2");
                showPop(view);
                return;
            case R.id.vehicle_origin:
                view.setTag("3");
                showPop(view);
                return;

            case R.id.shouye_btn_shangyexian_tianxiexinxi_xiayibu:
                intent = new Intent(this, BusinessInsuranceChooseLevelActivity.class);

                String applicant = ((EditText) findViewById(R.id.applicant)).getText().toString();
                //insurant_info  这个列表
                String name = ((EditText) findViewById(R.id.name)).getText().toString();
                String id_number = ((EditText) findViewById(R.id.id_number)).getText().toString();
                String tel = ((EditText) findViewById(R.id.tel)).getText().toString();
                String address = ((EditText) findViewById(R.id.address)).getText().toString();
                //
                String brand_model = ((EditText) findViewById(R.id.brand_model)).getText().toString();
                String plate_num = ((EditText) findViewById(R.id.plate_num)).getText().toString();
                String vin_code = ((EditText) findViewById(R.id.vin_code)).getText().toString();
                String engine_num = ((EditText) findViewById(R.id.engine_num)).getText().toString();
                String regtime = ((TextView) findViewById(R.id.regtime)).getText().toString();

                String carUsenature = useNature.getText().toString().replaceAll(" ", "");

                String passengers = ((EditText) findViewById(R.id.passengers)).getText().toString();
                String weight = ((EditText) findViewById(R.id.weight)).getText().toString();
                String driving_area = ((EditText) findViewById(R.id.driving_area)).getText().toString();


                if (TextUtils.isEmpty(applicant)) {
                    MyToast.showToast("请输入投保人姓名", context);
                    return;
                }
                if (TextUtils.isEmpty(picMap.get(1))) {
                    MyToast.showToast("请上传身份证照片", context);
                    return;
                }
                if (TextUtils.isEmpty(name)) {
                    MyToast.showToast("请输入被保险人名称", context);
                    return;
                }
                if (TextUtils.isEmpty(id_number)) {
                    MyToast.showToast("请输入被保险人身份证号", context);
                    return;
                }
                if (!Validator.isIDCard(id_number)) {
                    MyToast.showToast("身份证号码格式不正确", context);
                    return;
                }
                if (TextUtils.isEmpty(tel)) {
                    MyToast.showToast("请输入被保险人被保人联系电话", context);
                    return;
                }
                if (!Validator.isMobile(tel)) {
                    MyToast.showToast("手机号码格式不正确", context);
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    MyToast.showToast("请输入被保险人被保人联系地址", context);
                    return;
                }

                if (TextUtils.isEmpty(picMap.get(2))) {
                    MyToast.showToast("请上传行驶证和身份证照片", context);
                    return;
                }
                //被保车辆情况
                if (TextUtils.isEmpty(brand_model)) {
                    MyToast.showToast("请输入厂牌型号", context);
                    return;
                }
                if (TextUtils.isEmpty(plate_num)) {
                    MyToast.showToast("请输入号牌号码", context);
                    return;
                }
                if (!Validator.isCarNum(plate_num)) {
                    MyToast.showToast("车牌号码号码格式不正确", context);
                    return;
                }
                if (TextUtils.isEmpty(vin_code)) {
                    MyToast.showToast("请输入VIN码", context);
                    return;
                }
                if (TextUtils.isEmpty(engine_num)) {
                    MyToast.showToast("请输入发动机编号", context);
                    return;
                }
                if (TextUtils.isEmpty(carType.getText().toString())) {

                    MyToast.showToast("请输入车辆类型", context);
                    return;
                }
                if (TextUtils.isEmpty(carUsenature)) {

                    MyToast.showToast("请输入使用性质", context);
                    return;
                }

                if (carUsenature.equals("营运")) {

                    useNature.setTag("1");

                } else if (carUsenature.equals("非营运")) {

                    useNature.setTag("2");

                } else {

                    MyToast.showToast("请输入使用性质， 营运或非营运", context);
                    return;
                }

                if (TextUtils.isEmpty(regtime)) {
                    MyToast.showToast("请输入注册日期", context);
                    return;
                }
                if (TextUtils.isEmpty(passengers)) {
                    MyToast.showToast("请输入核定载客", context);
                    return;
                }
                if (TextUtils.isEmpty(weight) && useNature.getTag().toString().equals("1")) {
                    MyToast.showToast("货车请输入核定载质量", context);
                    return;
                }
                if (TextUtils.isEmpty(driving_area)) {
                    MyToast.showToast("请输入行驶区域", context);
                    return;
                }


                if (TextUtils.isEmpty(picMap.get(3))) {
                    MyToast.showToast("请上传人车照片", context);
                    return;
                }

                Bundle bundle = getIntent().getExtras();

                try {
                    JSONObject jsonObject = new JSONObject();//保险人信息

                    jsonObject.put("name", name);
                    jsonObject.put("id_number", id_number);
                    jsonObject.put("tel", tel);
                    jsonObject.put("address", address);

                    JSONObject jsonObject1 = new JSONObject();//被保险车辆信息

                    jsonObject1.put("brand_model", brand_model);
                    jsonObject1.put("plate_num", plate_num);
                    jsonObject1.put("vin_code", vin_code);
                    jsonObject1.put("engine_num", engine_num);
                    jsonObject1.put("use_nature", useNature.getTag().toString());
                    jsonObject1.put("vehicle_type", carType.getText().toString().replaceAll(" ", ""));
                    jsonObject1.put("regtime", regtime);
                    jsonObject1.put("passengers", passengers);
                    jsonObject1.put("weight", weight);
                    jsonObject1.put("driving_area", driving_area);
                    jsonObject1.put("vehicle_origin", vehicle_origin.getText().toString());


                    bundle.putString("vehicle_info", jsonObject1.toString());
                    bundle.putString("insurant_info", jsonObject.toString());

                    UtilLog.e("---vehicle_info----", jsonObject1.toString());
                    UtilLog.e("---insurant_info----", jsonObject.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                bundle.putString("applicant", applicant);

                bundle.putString("name", name);

                bundle.putString("brand_model", brand_model);

                //三个图片
                bundle.putString("id_url", picMap.get(1));
                bundle.putString("drive_url", picMap.get(2));
                bundle.putString("people_car_url", picMap.get(3));

                intent.putExtras(bundle);

                break;
        }
        startActivity(intent);
    }

    private void showPop(View view) {
        View contentView = LayoutInflater.from(context).inflate(R.layout.pop_layout, null);

        ListView popList = ((ListView) contentView.findViewById(R.id.item_popList));

        ArrayAdapter adapter = new ArrayAdapter<String>(context, R.layout.support_simple_spinner_dropdown_item, areaList);

        popList.setAdapter(adapter);

        final PopupWindow popupWindow = new PopupWindow(contentView, carType.getWidth(), ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setTouchable(true);

        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });

        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_white_bg));
        popupWindow.showAsDropDown(view);

        popList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                vehicle_origin.setText(areaList.get(position));

                popupWindow.dismiss();
            }
        });

    }

    public String bitmaptoString(Bitmap bitmap) {


        // 将Bitmap转换成字符串

        String string = null;

        ByteArrayOutputStream bStream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bStream);

        byte[] bytes = bStream.toByteArray();
        Base64Encoder base = new Base64Encoder();
        string = base.encode(bytes); //

        //  string = Base64.encodeToString(bytes, Base64.DEFAULT);

        return string;

    }


    @Override
    protected void resultPhotoPath(ImageView imageView, String s) {


        String str = bitmaptoString(PictureUtil.getSmallBitmap(s));

        String uid = BaseApplication.BasePreferences.readUserId();

        String time = System.currentTimeMillis() + "";

        String lock = UtilMD5.MD5Encode(UtilMD5.MD5Encode(uid + time, "UTF-8") + "zhang", "UTF-8");


        if (i == 1) {

            postIDCard.userid = uid;
            postIDCard.time = time;
            postIDCard.lock = lock;
            postIDCard.base = str;

            postIDCard.execute(this);

        } else if (i == 2) {

            postVehicleCard.userid = uid;
            postVehicleCard.time = time;
            postVehicleCard.lock = lock;
            postVehicleCard.base = str;

            postVehicleCard.execute(this);

        } else if (i == 3) {

            business_show_peopleCar_iv.setVisibility(View.VISIBLE);
            business_show_peopleCar_iv.setImageBitmap(PictureUtil.getSmallBitmap(s));


            ((Button) findViewById(R.id.peopleCar_submit)).setText("已选择");

        }


        picMap.put(i, s);


    }
}
